package com.customer.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.customer.mall.domain.vo.UserVO;
import com.customer.mall.mapper.UserMapper;
import com.customer.mall.domain.User;
import com.customer.mall.service.IUserService;
import com.customer.mall.util.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author BaiGGG
 * @since 2023-06-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    /**
     * 登录
     *
     * @param phone
     * @param password
     * @param verifyCode
     * @param session
     * @return
     */
    @Override
    public ResponseResult<User> login(String phone, String password, String verifyCode, HttpSession session) {

        // 数据校验
        if (!StringUtils.hasText(phone) || !StringUtils.hasText(password)) {
            return ResponseResult.failResult("账号密码不能为空!");
        }
        if (!StringUtils.hasText(verifyCode)) {
            return ResponseResult.failResult("验证码不能为空!");
        }
        if (!phone.matches("^\\d{11}$")) {
            return ResponseResult.failResult("手机号填写错误");
        }
        Object getCode = session.getAttribute("verifyCode");
        if (Objects.isNull(getCode)) {
            return ResponseResult.failResult("请获取验证码");
        }
        if (!getCode.toString().equals(verifyCode)) {
            return ResponseResult.failResult("验证码不正确");
        }
        String encodePassword = DigestUtils.md5DigestAsHex(password.getBytes());

        User getUser = getOne(new QueryWrapper<User>().eq("phone", phone).eq("password", encodePassword));
        if (Objects.isNull(getUser)) {
            return ResponseResult.failResult("用户不存在");
        }

        session.setAttribute("userId", getUser.getId());
        return ResponseResult.okResult();
    }

    /**
     * 注册
     *
     * @param phone
     * @param password1
     * @param password2
     * @param verifyCode
     * @param session
     * @return
     */
    @Override
    public ResponseResult<String> reg(String phone, String password1, String password2, String verifyCode, HttpSession session) {

        // 数据校验
        if (!StringUtils.hasText(phone) || !StringUtils.hasText(password1) || !StringUtils.hasText(password2)) {
            return ResponseResult.failResult("账号密码不能为空!");
        }
        if (!password1.equals(password2)) {
            return ResponseResult.failResult("输入的两次密码不相同");
        }
        if (!StringUtils.hasText(verifyCode)) {
            return ResponseResult.failResult("验证码不能为空!");
        }
        if (!phone.matches("^\\d{11}$")) {
            return ResponseResult.failResult("手机号填写错误");
        }
        Object getCode = session.getAttribute("verifyCode");
        if (Objects.isNull(getCode)) {
            return ResponseResult.failResult("请获取验证码");
        }

        if (!getCode.toString().equals(verifyCode)) {
            return ResponseResult.failResult("验证码不正确");
        }

        User getUser = getOne(new QueryWrapper<User>().eq("phone", phone));
        if (!Objects.isNull(getUser)) {
            return ResponseResult.failResult("用户已存在");
        }

        // 注册流程
        User saveUser = new User();
        saveUser.setPhone(phone);
        saveUser.setPassword(DigestUtils.md5DigestAsHex(password1.getBytes()));
        saveUser.setNickName("用户" + phone);
        if(!save(saveUser)){
            return ResponseResult.failResult("注册失败");
        }

        return ResponseResult.okResult("注册成功");
    }

    /**
     * 登出
     *
     * @param session
     * @return
     */
    @Override
    public ResponseResult<String> logout(HttpSession session) {
        Object userId = session.getAttribute("userId");
        if (Objects.isNull(userId)) {
            return ResponseResult.failResult("账号未登录");
        }
        session.removeAttribute("userId");
        return ResponseResult.okResult("退出成功");
    }

    /**
     * 判断是否已登录
     * @param session
     * @return
     */
    @Override
    public ResponseResult<UserVO> isLogin(HttpSession session) {
        Object userId = session.getAttribute("userId");
        if (Objects.isNull(userId)) {
            return ResponseResult.failResult("账号未登录");
        }
        return ResponseResult.okResult(getUserById(Long.parseLong(userId.toString())));
    }

    /**
     * 根据id获取用户
     * @param id
     * @return
     */
    @Override
    public UserVO getUserById(Long id){
        User getUser = getById(id);
        if(Objects.isNull(getUser)){
            return null;
        }
        UserVO resultUser = new UserVO();
        BeanUtils.copyProperties(getUser, resultUser);
        return resultUser;
    }

    @Override
    public ResponseResult<Page<UserVO>> pageUser(Integer pageNum, Integer pageSize) {
        Page<User> userPage = new Page<>(pageNum, pageSize);
        Page<UserVO> resUserVoPage = new Page<>();
        resUserVoPage.setRecords(page(userPage).getRecords().stream().map(item ->
            new UserVO(item.getId(), item.getNickName(), item.getPhone(), item.getCreateTime(), item.getUpdateTime())
        ).collect(Collectors.toList()));
        BeanUtils.copyProperties(userPage, resUserVoPage, "records");
        return ResponseResult.okResult(resUserVoPage);
    }

    @Override
    public ResponseResult<String> updateUser(User user) {
        if(!updateById(user)){
            return ResponseResult.failResult();
        }
        return ResponseResult.okResult();
    }


}
